/**
 * Created by duwei on 2019/3/26.
 */
var ZiPaiJavaManager = ZiPaiManager.extend({
    //房间状态
    roomStatus: {
        CREATED: 1,  // 刚创建
        PREPARING: 5,// 准备阶段
        ONGING: 2,   // 正在游戏
        GAMEOVER: 3, // 游戏结束
        ENDED: 4     // 房间解散
    },
    addListener: function (code, listener) {
        network.addListener(code, listener, this);
    },
    initListener: function () {
        /**
         * 玩家加入房间
         */
        this.addListener(3002, this.onUserJoin.bind(this));
        this.addListener(3003, this.onUserLeave.bind(this));
        this.addListener(3004, this.onReady.bind(this));
        this.addListener(3009, this.onGameVote.bind(this));
        this.addListener(4000, this.onTurnRow.bind(this));
        this.addListener(4001, this.onMoCard.bind(this));
        this.addListener(4002, this.onChuCard.bind(this));
        this.addListener(4003, this.showChiPengGangHu.bind(this));
        this.addListener(4005, this.onChiPengGangHu.bind(this));
        this.addListener(4006, this.onCardAscription.bind(this));
        this.addListener(4008, this.showGameResult.bind(this));
        this.addListener(4009, this.onRoomResult.bind(this));
        this.addListener(4020, this.onUserDisconnect.bind(this));
        this.addListener(4200, this.onCardDeal.bind(this));
        this.addListener(4062, this.setTingTipList.bind(this));
        this.addListener(4063, this.setHuTipList.bind(this));
        this.addListener(4100, this.showSelectPiao.bind(this));
        this.addListener(4102, this.onSelectedPiao.bind(this));
        this.addListener(5001, this.showSishou.bind(this));
    },
    /**
     * 设置玩法配置
     */
    setWanFaConfig: function () {
        if (this.MapId == app.map_id.XIANGXI_ERQISHI) {
            this.isDaiKan = false//是否带坎
        }
    },
    initRoomDate: function (data) {
        if (this.isReplay) {
            this.roomDate = data['3002']['data'];
            this.roomReplayDate = data;
            this.setCurRound(parseInt(gameData.recordIds[1]));
        } else {
            this.roomDate = data;
        }
        this.debuglog(this.roomDate);
        this.Option = this.roomDate['options'];
        this.setOption();
        this.ClubId = this.ClubId || this.roomDate['club_id'];
        this.Owner = this.roomDate['owner'];
        this.RoomID = this.roomDate['room_id'];
        this.isGameStart = false;
        if (!this.isReconnect) {
            this.GameStatus = this.roomStatus.CREATED;
            this.onUserJoin(this.roomDate);
            this.setUpPlayerPos(true);
        } else {//重连数据处理
            this.PlayerInfos = this.roomDate['players'];
            this.PlayersPais = this.roomDate['player_pai'];
            for (var i = 0; i < this.PlayerInfos.length; i++) {
                var playerInfo = this.PlayerInfos[i];
                var uid = playerInfo['uid'];
                this.g_uid_to_Score[uid] = playerInfo['total_score'];
                this.g_uid_to_InGameScore[uid] = playerInfo['total_score'];
            }
            for (i = 0; i < this.PlayersPais.length; i++) {
                var PlayersPai = this.PlayersPais[i];
                uid = PlayersPai['uid'];
                this.g_uid_to_Hands[uid] = PlayersPai['pai_arr'];
                this.g_uid_to_Menzi[uid] = PlayersPai['dui_arr'];
                this.g_uid_to_DiscardCards[uid] = PlayersPai['used_pai_arr'] || PlayersPai['used_mo_pai_arr'];
                this.g_uid_to_ChuCards[uid] = PlayersPai['used_chu_pai_arr'];
                this.g_uid_to_offline[uid] = !!PlayersPai['is_offline'];
                this.g_uid_to_Freeze[uid] = PlayersPai['louPaiArr'];
                this.g_uid_to_Piao[uid] = PlayersPai['piao'] || -1;
                this.g_uid_to_opencards[uid] = deepCopy(PlayersPai['dui_arr']) || [];
                if (PlayersPai['piao'] < 0 && this.withPiao) {
                    this.isAllPiao = false;
                }
                if (uid == gameData.uid) {
                    this.setSeverCardList(PlayersPai['pai_arr'], 'Reconnect');
                    this.setCardList();
                }
            }
            this.ShouxingID = this.roomDate['ShouxingID'];
            this.BankerUserID = this.roomDate['zhuang_uid'];
            this.GameStatus = this.roomDate['room_status'];
            this.setLeftCardCount(this.roomDate['left_pai_num']);
            this.setCurRound(this.roomDate['cur_round'] || 1);
            this.RoundInfo = {};
            this.RoundInfo['turn_uid'] = this.roomDate['turn_uid'];
            this.RoundInfo['will_chu'] = this.roomDate['will_chu'];
            this.RoundInfo['cur_pai'] = this.roomDate['cur_pai'];
            this.RoundInfo['isMoPai'] = this.roomDate['isMoPai'];
            this.isGameStart = (this.GameStatus == this.roomStatus.ONGING && this.isAllPiao);
            this.setUpPlayerPos(false);
        }
        this.setZiPaiRoomData();
    },
    setZiPaiRoomData: function () {
        this._super();
        gameData.wanfatype = 'java';
    },
    setUpPlayerPos: function (isInit) {
        gameData.players = this.PlayerInfos;
        this.PlayersNum = this.getPlayerNum();
        this.PlayerMap = {};
        var pos = 0;
        for (var i = 0; i < this.PlayerInfos.length; i++) {
            this.PlayerMap[this.PlayerInfos[i].uid] = this.PlayerInfos[i];
            if (this.PlayerInfos[i].uid == gameData.uid) {
                pos = i;
            }
        }
        this.pos0 = pos;
        this.pos1 = (pos + 1) % this.PlayersNum;
        this.pos2 = (pos + 2) % this.PlayersNum;
        this.pos3 = (pos + 3) % this.PlayersNum;

        this.g_pos_to_uid = {};
        this.g_uid_to_pos = {};
        this.g_uid_to_sex = {};
        this.g_pos_to_info = {};
        this.g_uid_to_info = {};
        this.g_uid_to_ready = {};
        this.g_uid_to_opencards = [];
        for (var i = 0; i < this.PlayersNum; i++) {
            var idx = this['pos' + i];
            var row = i;
            var info = this.PlayerInfos[idx];
            if (info) {
                this.g_pos_to_info[row] = info;
                this.g_pos_to_uid[row] = info.uid;
                this.g_uid_to_pos[info.uid] = row;
                this.g_uid_to_sex[info.uid] = info.sex || 1;
                this.g_uid_to_info[info.uid] = info;
                this.g_uid_to_ready[info.uid] = info['ready'];
                if (info.uid == gameData.uid) {
                    this.isShowReadyBtn = (!info['ready'] && this.GameStatus != this.roomStatus.ONGING);
                }
            }
        }
        if (!isInit) {
            eventManager.dispatchEvent(ZiPaiEvent.UpPlayerPos);
            eventManager.dispatchEvent(EventKey.ClubRoomPlayerStateRefresh);
            eventManager.dispatchEvent(EventKey.ClubPlayerEnterExit, gameData.players);
        }
    },
    /**
     * 玩家加入
     * code 3002
     * @param data
     */
    onUserJoin: function (data) {
        this.debuglog('onUserJoin');
        this.debuglog(data);
        this.PlayerInfos = data['players'];
        this.setUpPlayerPos();
    },
    /**
     * 玩家离开
     * code 3003
     * @param data
     */
    onUserLeave: function (data) {
        this.debuglog('onUserLeave');
        this.debuglog(data);
        var self = this;
        var uid = data['uid'];
        if (uid == gameData.uid) {
            showBoard('HallBoard');
            return;
        }
        if (data['del_room']) {
            var owner = self.g_uid_to_info[self.Owner];
            if (owner) {
                showAlert('房主' + owner.nickname + '已解散房间', function () {
                    showBoard('HallBoard');
                });
            } else {
                showAlert('房主已解散房间', function () {
                    showBoard('HallBoard');
                });
            }
        }
        else {
            _.remove(this.PlayerInfos, function (player) {
                return player.uid == uid;
            });
            this.setUpPlayerPos();
        }
    },
    /**
     * 玩家准备
     * code 3004
     * @param data
     */
    onReady: function (data) {
        this.debuglog('onReady');
        this.debuglog(data);
        if (!data)
            return;
        var uid = data['uid'];
        this.g_uid_to_ready[uid] = 1;
        if (uid == gameData.uid) {
            this.isShowReadyBtn = false;
        }
        eventManager.dispatchEvent(ZiPaiEvent.PlayersStatus);
    },
    /**
     * 申请解散
     * code 3009
     * @param data
     */
    onGameVote: function (data, errorCode) {
        this.debuglog('onGameVote');
        this.debuglog(data);
        if (errorCode == -1) {
            showAlert("长时间未开始,房间自动解散");
            return
        }
        if (data["arr"] == null || data["arr"] == undefined || data["arr"] == '' || (data["arr"] && data["arr"].length == 0)) {
            return;
        }
        var that = this;
        var arr = data['arr'];
        var leftSeconds = data['left_sec'];
        leftSeconds = (leftSeconds < 0 ? 0 : leftSeconds);
        var byUserId = data['arr'][0].uid;
        if (that.isJiesan)
            return;
        that.isJiesan = data['is_jiesan'];

        var RoomQuitWindow = window.curScene.getChildByName('RoomQuitWindow');
        if (!RoomQuitWindow) {
            RoomQuitWindow = showWindow('RoomQuitWindow', leftSeconds, arr, byUserId, data);
        } else {
            RoomQuitWindow.setData(leftSeconds, arr, byUserId, data);
            RoomQuitWindow.setVisible(true);
        }
    },
    /**
     * 转换操作人
     * code 4000
     * @param data
     */
    onTurnRow: function (data) {
        this.debuglog('onTurnRow');
        this.debuglog(data);
        //{"code":4000,"data":{"room_id":526090,"uid":218},"errorCode":0}
        eventManager.dispatchEvent(ZiPaiEvent.onTurnRow, data);
    },
    /**
     * 摸牌
     * code 4001
     * @param data
     */
    onMoCard: function (data) {
        this.debuglog('onMoCard');
        this.debuglog(data);
        this.LeftCardCount = data['left'];
        eventManager.dispatchEvent(ZiPaiEvent.onMoCard, data);
        var uid = data['uid'];
        if (uid == gameData.uid) {
            this.TishiList = [];
            eventManager.dispatchEvent(ZiPaiEvent.TishiList);
        }
    },
    /**
     * 出牌
     * code 4002
     * @param data
     */
    onChuCard: function (data) {
        this.debuglog('onChuCard');
        this.debuglog(data);
        eventManager.dispatchEvent(ZiPaiEvent.onChuCard, data);
    },
    /**
     * 保留自己摆牌，设置手牌
     */
    setChiPengCardList: function () {
        var severCardList = deepCopy(this.SeverCardList);
        cc.log(deepCopy(severCardList));
        var deleteCard = function (cardId) {
            for (var i = 0; i < severCardList.length; i++) {
                if (severCardList[i] == cardId) {
                    severCardList.splice(i, 1);
                    cc.log(deepCopy(severCardList));
                    return true
                }
            }
            return false;
        };
        cc.log(deepCopy(this.CardList));
        for (var k = this.CardList.length -1; k >=0; k--) {
            var Cards = this.CardList[k];
            for (var i = Cards.length-1; i >= 0; i--) {
                var cardId = Cards[i];
                if(!deleteCard(cardId)){
                    cc.log('card',k,i)
                    Cards.splice(i, 1);
                }
            }
            if(Cards.length == 0){
                cc.log('Cards',k)
                this.CardList.splice(k, 1);
            }
        }
        cc.log(deepCopy(this.CardList));
    },
    /**
     * 显示吃碰杠胡动画
     * code 4003
     * @param data
     */
    showChiPengGangHu: function (data) {
        this.debuglog('showChiPengGangHu');
        this.debuglog(data);
        var uid = data['uid'];
        var row = this.g_uid_to_pos[uid];
        if (row == 0 && data['pai_arr']) {
            this.setSeverCardList(data['pai_arr']);
            if (data['louPaiArr']) {
                this.g_uid_to_Freeze[uid] = data['louPaiArr'];
            }
            if (this.room.chiPengCardDeal) {
                this.setChiPengCardList();
            } else {
                this.setCardListByDel(data['pai_id'], data['op']);
            }
            this.TingCards = [];
            eventManager.dispatchEvent(ZiPaiEvent.TingCards);
            eventManager.dispatchEvent(ZiPaiEvent.CardDeal);
        }
        if (this.isReplay && row > 0 && data['pai_arr']) {
            this.setOtherCardList(data['pai_arr'], row);
            eventManager.dispatchEvent(ZiPaiEvent.UpOtherCards, row);
        }
        eventManager.dispatchEvent(ZiPaiEvent.showChiPengGangHu, data);
    },
    /**
     * 检测比是否有效
     */
    biIsValid : function (paiArr, comPaiArr){
        var self = this;
        var opPaiId = this.opId;
        var dui = [];
        var comDui = [];

        for (var i = 0; i < paiArr.length; i++){
            dui[i] = paiArr[i];
            comDui[i] = comPaiArr[i];
        }
        dui.sort(
            function (a, b) {
                return a - b;
            }
        );
        comDui.sort(
            function (a, b) {
                return a - b;
            }
        );

        //合法性检测
        if (dui.length != 3 || comDui.length != 3) return false;
        //检测comDui是否是绞牌
        if (comDui[0] == comDui[1] || comDui[0] == comDui[2] || comDui[1] == comDui[2]) return true;
        //检测2 7 10
        if ((dui[0] == 2 && dui[1] == 7) || (dui[0] == 12 && dui[1] == 17)) return false;
        if ((comDui[0] == 2 && comDui[1] == 7) || (comDui[0] == 12 && comDui[1] == 17)) return false;
        //comDui中间的牌是吃的牌
        if (opPaiId == comDui[1]) return false;
        //检测dui是顺子
        var duiIsABC = dui[0] == (dui[1] - 1) && dui[0] == (dui[2] - 2);
        if (duiIsABC){
            if (opPaiId == dui[1]) return false;
            else {
                if (Math.abs(dui[0] - comDui[0]) == 2) return true;
                else return false;
            }
        }
        else {
            return true;
        }

        return false;
    },
    setChiArray: function () {
        if (this.ChiList == null || this.ChiList == undefined) {
            this.ChiArray = null;
            return;
        }
        this.ChiArray = [];
        for (var i = 0; i < this.ChiList.length; i++) {
            var chionei = [];
            if (this.ChiList[i]['paiArr'].length > 0) {
                for (var j = 0; j < this.ChiList[i]['paiArr'].length; j++) {
                    chionei.push(this.ChiList[i]['paiArr'][j]);
                }
            }
            if (this.ChiList[i]['biList'].length > 0) {
                var chionex = [];
                for (var j = 0; j < this.ChiList[i]['biList'].length; j++) {
                    var chionej = [];
                    for (var l = 0; l < this.ChiList[i]['biList'][j]['paiArr'].length; l++) {
                        chionej.push(this.ChiList[i]['biList'][j]['paiArr'][l]);
                    }
                    //
                    if (this.ChiList[i]['biList'][j]['biList'].length > 0) {
                        var chioney = [];
                        for (var k = 0; k < this.ChiList[i]['biList'][j]['biList'].length; k++) {
                            var chionek = this.ChiList[i]['biList'][j]['biList'][k]['paiArr'];
                            chioney.push(chionek);
                        }
                        chionej.push(chioney);
                    }
                    chionex.push(chionej);
                }
                chionei.push(chionex);
            }
            this.ChiArray.push(chionei);

        }
        this.debuglog('setChiArray');
        this.debuglog(this.ChiArray);
    },
    /**
     * 吃碰杠胡
     * code 4005
     * @param data
     */
    onChiPengGangHu: function (data) {
        this.debuglog('onChiPengGangHu');
        this.debuglog(data);
        this.ChiList = data['tishi'][0]['chiList'];
        //屏蔽
        //this.opId = data['tishi'][0]['pai_id'];
        this.setChiArray();
        //{"code":4005,"data":{"room_id":840203,"uid":217,"tishi":{"pai_id":20,"op":[true,false,false]}},"errorCode":0}
        eventManager.dispatchEvent(ZiPaiEvent.onChiPengGangHu, data);
    },
    /**
     * 牌归属
     * code 4006
     * @param data
     */
    onCardAscription: function (data) {
        this.debuglog('onCardAscription');
        this.debuglog(data);
        eventManager.dispatchEvent(ZiPaiEvent.onCardAscription, data);
    },
    /**
     * 小结算
     * code 4008
     * @param data
     */
    showGameResult: function (data) {
        this.debuglog('showGameResult');
        // return ;
        this.debuglog(data);
        this.GameStatus = this.roomStatus.ENDED;
        this.gameOverData = data;
        var players = data['players'];
        for (var i = 0; i < players.length; i++) {
            var player = players[i];
            var uid = player['uid'];
            var row = this.g_uid_to_pos[uid];
            this.g_uid_to_Score[uid] = player['total_score'];
            if (uid != gameData.uid) {
                this['CardList' + row] = mCard.getCardList(player['shoupai']);
            }
        }
        //准备状态设置成0
        for (var key in this.g_uid_to_ready){
            var uid = key;
            this.g_uid_to_ready[uid] = 0;
        }
        eventManager.dispatchEvent(ZiPaiEvent.showGameResult, true);
    },
    /**
     * 房间结算
     * code 4009
     * @param data
     */
    onRoomResult: function (data) {
        this.debuglog('onRoomResult');
        this.debuglog(data);
        this.RoomResultDate = data;
        // if (this.isjiesanSucess) {
        //     eventManager.dispatchEvent(ZiPaiEvent.RoomResult);
        // }
    },
    /**
     * 玩家临时掉线
     * code 4020
     * @param data
     */
    onUserDisconnect: function (data) {
        this.debuglog('onUserDisconnect');
        this.debuglog(data);
        var uid = data['uid'];
        this.g_uid_to_offline[uid] = data['is_offline'];
        eventManager.dispatchEvent(ZiPaiEvent.UserDisconnect);
    },
    /**
     * 听牌提示
     * 4062
     * @param data
     */
    setTingTipList: function (data) {
        this.debuglog('setTingTipList');
        this.debuglog(data);
        this.TingCards = [];
        this.TishiList = data['tishi'];
        eventManager.dispatchEvent(ZiPaiEvent.TishiList);
    },
    /**
     * 胡牌提示
     * 4063
     * @param data
     */
    setHuTipList: function (data) {
        this.debuglog('setHuTipList');
        this.debuglog(data);
        this.TingCards = data['tishi'];
        eventManager.dispatchEvent(ZiPaiEvent.TingCards);
    },
    /**
     * 显示选票
     * 4100
     * @param data
     */
    showSelectPiao: function (data) {
        this.debuglog('showSelectPiao');
        this.debuglog(data);
        this.setCurRound(data['cur_round']);
        this.isGameStart = true;
        eventManager.dispatchEvent(ZiPaiEvent.StatusChange);
        eventManager.dispatchEvent(ZiPaiEvent.GameStart);
        eventManager.dispatchEvent(EventKey.ClubRoomGameStart);
        eventManager.dispatchEvent(ZiPaiEvent.showSelectPiao, data);
    },
    /**
     * 选票
     * 4102
     * @param data
     */
    onSelectedPiao: function (data) {
        this.debuglog('onSelectedPiao');
        this.debuglog(data);
        this.isAllPiao = data['is_finished'];
        eventManager.dispatchEvent(ZiPaiEvent.onSelectedPiao, data);
    },
    /**
     * 开始发牌
     * code 4200
     * @param data
     */
    onCardDeal: function (data) {
        this.debuglog('onCardDeal');
        this.debuglog(data);
        this.isGameStart = true;
        this.BankerUserID = data['zhuang_uid'];
        this.GameStatus = 2;
        this.setCurRound(data['cur_round']);
        this.clearGameDate();
        eventManager.dispatchEvent(ZiPaiEvent.StatusChange);
        eventManager.dispatchEvent(ZiPaiEvent.GameStartAnimation);
        eventManager.dispatchEvent(ZiPaiEvent.GameStart);
        eventManager.dispatchEvent(EventKey.ClubRoomGameStart);

        var uid = data['uid'];
        var pos = this.g_uid_to_pos[uid];
        if (pos == 0) {
            this.setLeftCardCount(data['left'], 'onCardDeal');
            this.setSeverCardList(data['paiArr']);
            this.setCardList();
            var isZhuangId = this.BankerUserID == gameData.uid;
            var isBlockFapai = isZhuangId ? true : false;
            eventManager.dispatchEvent(ZiPaiEvent.CardDeal, {isReplay:this.isReplay, isFapai:true, isBlock:isBlockFapai});
        } else {
            this.setOtherCardList(data['Cards'], pos);
            eventManager.dispatchEvent(ZiPaiEvent.UpOtherCards, pos);
        }
    },
    /**
     * 死守
     * code 5001
     * @param data
     */
    showSishou: function (data) {
        this.debuglog('showSishou');
        this.debuglog(data);
        //{"code":4000,"data":{"room_id":526090,"uid":218},"errorCode":0}
        //eventManager.dispatchEvent(ZiPaiEvent.onTurnRow, data);
        eventManager.dispatchEvent(ZiPaiEvent.onShowSishou, data);
    },
});
